var express = require('express');
var router = express.Router();
var filter = require('../tools/filter.js');
var validate = require('../tools/validate.js');
var usermodel = require('../model/user.js');
var tools = require('../tools/utils.js');

/* GET home page. */
router.get('/admin', filter.authorize, function(req, res, next) {
    res.redirect('/admin/home');
});
router.get('/admin/:action', function(req, res, next) {
    var action = req.params.action;
    var title;
    if (action == 'reg') {
        title = "注册页面";
    } else if (action == 'home') {
        title = "主页面";
    } else {
        title = "登陆页面";
    }
    res.render('index', { title: title, templ: action });
});


router.post('/admin/doLogin', function(req, res, next) {
    console.log('do login');
    var user = {};
    user.username = req.body.username;
    user.pwd = req.body.pwd;
    validate.notEmpty([user.username, user.pwd], function(err) {
        if (err.length > 0) {
            console.log(err);
            res.redirect('/admin/login');
        } else if (usermodel.checkUser(user)) {
            req.session.user_id = user.username;
            req.session.user = user;
            res.redirect('/admin/home');

        } else {
            res.send(502, { message: "用户没注册" });
        }
    });
});

router.post('/admin/doReg', function(req, res, next) {
    console.log('do reg');
    var user = {};
    user.username = req.body.username;
    user.pwd = req.body.pwd;
    validate.notEmpty([user.username, user.pwd], function(err) {
        if (err.length > 0) {
            console.log(err);
            res.redirect('/admin/reg');
        } else {
            user._id = tools.guid();
            usermodel.reg(user, function(err) {
                if (err) {
                    res.send(500, { message: err });
                } else {
                    res.sendStatus(200);
                }
            });
        }
    });
});

module.exports = router;
